﻿using System;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Data;
using System.Collections.Generic;
using WebSite.Admin.Core;

namespace WebSite.Admin
{
    public partial class Admin_Trivia : AdminBasePage
    {

        // Coded by wenbin 2012-10-8 18:00:20
        #region 实体类
        /// <summary>
        /// 实体类
        /// </summary>
        private class Trivia
        {
            private int _id = 0;
            public int Id
            {
                get { return _id; }
                set { _id = value; }
            }
            private int _cityType = 0;
            public int CityType
            {
                get { return _cityType; }
                set { _cityType = value; }
            }
            private string _imageSmall = string.Empty;
            public string ImageSmall
            {
                get { return _imageSmall; }
                set { _imageSmall = value; }
            }
            private string _imageBig = string.Empty;
            public string ImageBig
            {
                get { return _imageBig; }
                set { _imageBig = value; }
            }
            private int _orderBy = 0;
            public int OrderBy
            {
                get { return _orderBy; }
                set { _orderBy = value; }
            }
            private int _status = 0;
            public int Status
            {
                get { return _status; }
                set { _status = value; }
            }

        }
        #endregion

        dbHelper db = new dbHelper();

        /// <summary>
        /// 查询id
        /// </summary>
        public long QId
        {
            get
            {
                return Convert.ToInt64( Request.QueryString["id"] );
            }
        }

        protected override void OnInit( EventArgs e )
        {
            base.OnInit( e );
        }


        protected void Page_Load( object sender, EventArgs e )
        {
            string redirectUrl = HttpContext.Current.Request.Url.ToString().Split( '?' )[0];
            int page = Convert.ToInt32( Request.QueryString["page"] );
            if (page == 0)
                page = 1;
            string urlPage = "page=" + page;
            string strWhere = " 1=1 ";
            string urlParams = "";
            string searchId = dbHelper.FilterSql( Request.QueryString["searchId"] );
            if (!string.IsNullOrEmpty( searchId ))
            {
                strWhere += " and Id =" + searchId + "";
                urlParams += "&searchId=" + searchId;
            }
            string searchCityType = dbHelper.FilterSql( Request.QueryString["searchCityType"] );
            if (!string.IsNullOrEmpty( searchCityType ))
            {
                strWhere += " and CityType =" + searchCityType + "";
                urlParams += "&searchCityType=" + searchCityType;
            }
            string searchImageSmall = dbHelper.FilterSql( Request.QueryString["searchImageSmall"] );
            if (!string.IsNullOrEmpty( searchImageSmall ))
            {
                strWhere += " and ImageSmall like '%" + searchImageSmall + "%'";
                urlParams += "&searchImageSmall=" + searchImageSmall;
            }

            string searchImageBig = dbHelper.FilterSql( Request.QueryString["searchImageBig"] );
            if (!string.IsNullOrEmpty( searchImageBig ))
            {
                strWhere += " and ImageBig like '%" + searchImageBig + "%'";
                urlParams += "&searchImageBig=" + searchImageBig;
            }
            string searchOrderBy = dbHelper.FilterSql( Request.QueryString["searchOrderBy"] );
            if (!string.IsNullOrEmpty( searchOrderBy ))
            {
                strWhere += " and OrderBy =" + searchOrderBy + "";
                urlParams += "&searchOrderBy=" + searchOrderBy;
            }
            string searchStatus = dbHelper.FilterSql( Request.QueryString["searchStatus"] );
            if (!string.IsNullOrEmpty( searchStatus ))
            {
                strWhere += " and Status =" + searchStatus + "";
                urlParams += "&searchStatus=" + searchStatus;
            }

            urlPage = urlPage + urlParams;
            if (!string.IsNullOrEmpty( urlParams ))
                urlParams = urlParams.Substring( 1, urlParams.Length - 1 );
            redirectUrl = redirectUrl + "?" + urlPage;

            //数据导出
            string toExcel = dbHelper.FilterSql( Request.QueryString["toExcel"] );
            if (toExcel == "1")
            {
                ExcelSubmit( strWhere );
            }

            //分页
            Paging( page, strWhere, urlParams );

            //业务
            BussessOper( redirectUrl );


        }

        #region  --数据导出---

        /// <summary>
        /// 保存xls文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExcelSubmit( string sWhere )
        {
            string sSelect = "Id as 'Id',CityType as '城市',ImageSmall as '小图片',ImageBig as '大图片',OrderBy as '排序',Status as '状态 0屏蔽 1打开'";

            string some_search = string.Format( "select {0} from Trivia(nolock) where {1} ", sSelect, sWhere ); //查询语句
            DataSet ds = db.returndataset( null, some_search, null, null );

            //填冲到XLS中////
            AdminCommon.xlsGridview( ds, string.Format( "数据_{0}", DateTime.Now ) );
        }

        #endregion


        #region 分页
        public void Paging( int page, string strWhere, string urlParams )
        {
            dbHelper.pageproret record = new dbHelper.pageproret();

            record = db.GetPageRecordSet( "Trivia", page, 20, "Id", "Id Desc", "*", strWhere );
            int pagecount = record.pagecount;
            DataTable dt = record.recordset;
            List<Trivia> datasrc = db.ConvertTo<Trivia>( dt ).ToList();

            DataList.DataSource = datasrc.Count > 0 ? datasrc : null;
            DataList.DataBind();

            string pager = db.BuildPager( page, pagecount, "", urlParams );
            sPage.Text = pager;
        }

        #endregion

        #region 业务处理
        /// <summary>
        /// 业务处理
        /// </summary>
        /// <param name="redirectUrl"></param>
        public void BussessOper( string redirectUrl )
        {
            if (Request.QueryString["act"] == "del")
            {
                if (QId != 0)
                {
                    DeleteData( QId );
                    Response.Redirect( redirectUrl );
                }
            }

            if (Request.ServerVariables["REQUEST_METHOD"] == "POST")
            {
                string idStr = dbHelper.FilterSql( Request.Form["SelectID"] );
                if (!string.IsNullOrEmpty( idStr ))
                {
                    idStr = idStr.Replace( " ", "" );
                    idStr = idStr.Replace( "&nbsp;", "" );
                    if (!string.IsNullOrEmpty( Request.Form["delete"] ))
                    {
                        DeleteBatchData( idStr );
                        Response.Redirect( redirectUrl );
                    }
                    if (!string.IsNullOrEmpty( Request.Form["pingbi"] ))
                    {
                        SwitchBatchData( 0, idStr );
                        Response.Redirect( redirectUrl );
                    }
                    if (!string.IsNullOrEmpty( Request.Form["fabu"] ))
                    {
                        SwitchBatchData( 1, idStr );
                        Response.Redirect( redirectUrl );
                    }
                    Response.Redirect( redirectUrl );
                    Response.End();
                }
                Trivia sdata = new Trivia();

                //string modid = Request.Form["ModId"] == null ? "0" : Request.Form["ModId"].Trim();
                //int id =sdata.Id = Convert.ToInt32(modid);
                sdata.Id = Convert.ToInt32( dbHelper.FilterSql( Request.Form["ModId"].Trim() ) ?? "" );
                sdata.CityType = Convert.ToInt32( dbHelper.FilterSql( Request.Form["ModCityType"].Trim() ) ?? "" );
                sdata.ImageSmall = Convert.ToString( dbHelper.FilterSql( Request.Form["ModImageSmall"].Trim() ) ?? "" );
                //

                string fileImageBig = string.Empty;
                if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
                {
                    try
                    {
                        System.Drawing.Image img = System.Drawing.Image.FromStream( Request.Files[0].InputStream );
                        if (Request.Files[0].ContentLength > 500 * 1024)
                        {
                            base.AlertMessageBack( "图片大小不能超过500K" );
                        }

                        string fileName = Guid.NewGuid().ToString( "N" ) + Path.GetExtension( Request.Files[0].FileName );
                        Request.Files[0].SaveAs( MapPath( "/UploadImages/Highlight/" + fileName ) );
                        fileImageBig = "/UploadImages/Highlight/" + fileName;
                        sdata.ImageBig = fileImageBig;
                    }
                    catch (Exception ex)
                    {
                        base.AlertMessageBack( "保存失败：" + ex.Message );
                        // context.Response.Write( "上传文件失败" );
                    }
                }
                else
                {
                    sdata.ImageBig = Convert.ToString( dbHelper.FilterSql( Request.Form["ModImageBig"].Trim() ) ?? "" );
                }

                sdata.OrderBy = Convert.ToInt32( dbHelper.FilterSql( Request.Form["ModOrderBy"].Trim() ) ?? "" );
                sdata.Status = Convert.ToInt32( dbHelper.FilterSql( Request.Form["ModStatus"].Trim() ) ?? "" );
                var id = sdata.Id;
                if (id == 0)
                {
                    //增加
                    if (InsertData( sdata ))
                    {
                        Response.Redirect( redirectUrl );
                        Response.End();
                    }
                    else
                    {
                        Response.Write( "error" );
                        Response.End();
                    }
                }
                else
                {
                    //修改
                    if (UpdateData( sdata ))
                    {
                        Response.Redirect( redirectUrl );
                        Response.End();
                    }
                    else
                    {
                        Response.Write( "error" );
                        Response.End();
                    }
                }
            }
        }
        #endregion


        #region 增删改

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="sdata"></param>
        /// <returns></returns>
        private bool InsertData( Trivia sdata )
        {
            string sqlStr = @"INSERT INTO Trivia(
					[CityType],
							[ImageSmall],
							[ImageBig],
							[OrderBy],
							[Status]	)VALUES(
					@CityType,
							@ImageSmall,
							@ImageBig,
							@OrderBy,
							@Status)";
            SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@CityType",sdata.CityType),
							new SqlParameter("@ImageSmall",sdata.ImageSmall),
							new SqlParameter("@ImageBig",sdata.ImageBig),
							new SqlParameter("@OrderBy",sdata.OrderBy),
							new SqlParameter("@Status",sdata.Status)};
            int ret = db.GetExecuteNonQuery( null, sqlStr, parms );
            return ret > 0;
        }


        /// <summary>
        /// 修改数据
        /// </summary>		
        /// <param name="sdata"></param>
        /// <returns></returns>
        private bool UpdateData( Trivia sdata )
        {
            string sqlStr = @"UPDATE Trivia SET
					[CityType]=@CityType,
										[ImageSmall]=@ImageSmall,
										[ImageBig]=@ImageBig,
										[OrderBy]=@OrderBy,
										[Status]=@Status WHERE Id=@Id";

            SqlParameter[] parms = new SqlParameter[] {
					new SqlParameter("@Id",sdata.Id),
										new SqlParameter("@CityType",sdata.CityType),
										new SqlParameter("@ImageSmall",sdata.ImageSmall),
										new SqlParameter("@ImageBig",sdata.ImageBig),
										new SqlParameter("@OrderBy",sdata.OrderBy),
										new SqlParameter("@Status",sdata.Status)};
            int ret = db.GetExecuteNonQuery( null, sqlStr, parms );
            return ret > 0;
        }


        /// <summary>
        ///单个删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool DeleteData( long id )
        {
            string sqlStr = string.Format( "DELETE FROM Trivia WHERE Id={0}", id );

            int ret = db.GetExecuteNonQuery( null, sqlStr, null );
            return ret > 0;
        }
        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="idStr"></param>
        /// <returns></returns>
        private bool DeleteBatchData( string idStr )
        {
            string sqlStr = string.Format( "DELETE FROM Trivia WHERE Id IN ({0})", idStr );

            int ret = db.GetExecuteNonQuery( null, sqlStr, null );
            return ret > 0;
        }


        /// <summary>
        /// 状态操作
        /// </summary>
        /// <param name="optype"></param>
        /// <param name="idStr"></param>
        /// <returns></returns>
        private bool SwitchBatchData( int optype, string idStr )
        {
            string sqlStr = "";
            if (optype == 0)
                sqlStr = string.Format( "UPDATE Trivia SET [Status]=0 WHERE Id IN ({0})", idStr );
            else
                sqlStr = string.Format( "UPDATE Trivia SET [Status]=1 WHERE Id IN ({0})", idStr );

            int ret = db.GetExecuteNonQuery( null, sqlStr, null );
            return ret > 0;
        }



        #endregion
    }
}


